include("shared.lua");
AddCSLuaFile("cl_init.lua");
AddCSLuaFile("shared.lua");

function ENT:Setup ()
	self.Loltiem = CurTime();
	self.asploded = false;
	self.Maxlol = self.Healthlol;
	self.notflaming = true;
	self.Stance = 0;
	if self.Move ~= nil && self.TargetVec == nil then
	self.TargetVec = { };
	end
	self.Target = nil;
	self.infot = ents.Create("info_target");
	self.infot:SetPos(self.Entity:GetPos());
	self.infot:Spawn();
	self.infot:Activate();
	self.infot:SetParent(self.Entity);
	self.infot.Warmelon = true;
	self.infot.Team = self.Team;
	self.Entity:SetModel(self.MelonModel);
	self.Entity:PhysicsInit(SOLID_VPHYSICS);
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS);
	self.Entity:SetSolid(SOLID_VPHYSICS);
	self.Entity:SetMaterial("models/debug/debugwhite");
	local physics = self.Entity:GetPhysicsObject();
	if (physics:IsValid()) then
		physics:Wake();
		physics:SetBuoyancyRatio(0.2)
		physics:EnableGravity(self.Grav);
		if (self.Team == 1) then
		self.Entity:SetColor (255, 0, 0, 255);
		end
		if (self.Team == 2) then
		self.Entity:SetColor (0, 0, 255, 255);
		end
		if (self.Team == 3) then
		self.Entity:SetColor (0, 255, 0, 255);
		end
		if (self.Team == 4) then
		self.Entity:SetColor (255, 255, 0, 255);
		end
		if (self.Team == 5) then
		self.Entity:SetColor (255, 0, 255, 255);
		end
		if (self.Team == 6) then
		self.Entity:SetColor (0, 255, 255, 255);
		end
	end
end

function ENT:BeforeDeathFunc ()
end

function ENT:OtherThoughts ()
end

function ENT:DoMoves ()
if self.Damping == nil then
self.Damping = 1.2
end

local leaderrange = -5;
if self.FollowRange == nil then
self.FollowRange = 50;
end

	if (self.Leader && self.Leader:IsValid()) then
	leaderrange = self.Entity:GetPos():Distance(self.Leader:GetPos())
	  if (leaderrange > self.FollowRange && self.TargetVec[2] == nil) then
    self.TargetVec[1] = self.Leader:GetPos();
		self.Orders = true;
	  end
  else
  leaderrange = 100000
  end
  
if self.Stance ~= 0 then
  if self.Stance > 0 && self.Target ~=nil && self.Target:IsValid() && self.Target:GetPos():Distance(self.Entity:GetPos()) < 1500 then
  	local traceRes=util.QuickTrace (self.Entity:GetPos(), self.Target:GetPos()-self.Entity:GetPos(), self.Entity);
  	if traceRes.Entity == self.Target && !self.Target:GetTable().asploded then
      if self.Stance == 1 or self.Stance == 2 then
      self:Chase();
      end
    self.Stance = self.Stance * -1
    end
  end
  if self.Stance < 0 && self.Stance > -4 then
  self.Leader = self.Target
  self.Orders = true
  self.TargetVec = {}
  if self.Target:IsValid() then
  self.TargetVec[1] = self.Target:GetPos()
  end
    if self.Stance == -1 then
      if self.Entity:GetPos():Distance(self.StartChase) > 1500 || !self.Target:IsValid() then
      self:GoHome()
      end
    end
    if self.Stance == -2 then
      if self.Entity:GetPos():Distance(self.Target) > 1500 || !self.Target:IsValid() then
      self:GoHome()
      end
    end
  end
  if self.Stance < -4 && self.StartChase ~= nil && self.Entity:GetPos():Distance(self.StartChase) < 50 then
  self.Stance = self.Stance * -0.2
  self.Leader = self.Leader2
  self.Leader2 = nil
  self.Patrol = self.Patrol2
  self.Patrol2 = nil
  end
end



local melonspeed = server_settings.Int( "WM_Melonspeed", 1 );
  if self.TargetVec[1] ~= nil then
	local angle1 = self.TargetVec[1] - self.Entity:GetPos();
	if self.Entity:GetPos():Distance(self.TargetVec[1])>self.NoMoveRange && self.Orders then
			self.Entity:GetPhysicsObject():SetDamping(0, 0);
			self.Entity:GetPhysicsObject():ApplyForceCenter (angle1:Normalize() * self.MovingForce * melonspeed);	
	else
	
		if self.Move then
			if self.Patrol == 1 then
			table.insert(self.TargetVec, table.remove(self.TargetVec, 1))
			else
			table.remove(self.TargetVec, 1)
			end
		
			   if self.Leader == nil || leaderrange < self.FollowRange then
			    if self.TargetVec[1] == nil then
	           if self.Grav == 0 then
	           self.Entity:SetVelocity(self.Entity:GetVelocity() * 0.05)
	           end
			   	   if self.Entity:GetPhysicsObject():IsValid() then
			       self.Entity:GetPhysicsObject():SetDamping(self.Damping, 0);
			       end
			    self.Orders = false;
			    end
			   end
			end
		end
	end
end

function ENT:Chase()
self.Patrol2 = self.Patrol
self.TargetVec2 = {}
self.TargetVec2 = table.Copy(self.TargetVec)
self.Leader2 = self.Leader
self.StartChase = self.Entity:GetPos()
end

function ENT:GoHome()
self.TargetVec = {}
self.TargetVec = table.Copy(self.TargetVec2)
self.TargetVec2 = {}
table.insert(self.TargetVec, 1, self.StartChase)

--if there's a valid leader here they will NOT go back to their start location, they will go to the leader.
self.Orders = true
self.Stance = self.Stance * 5
end

function ENT:DoAttacks ()
if server_settings.Int( "WM_Pause", 0 ) ~= 1 && self.HoldFire ~= 1 then
	if self.Target == nil || !self.Target:IsValid() then
		self:TargetSearch();
		return
	end
	local traceRes=util.QuickTrace (self.Entity:GetPos(), self.Target:GetPos()-self.Entity:GetPos(), self.Entity);
	--Checking that the target is still in range, and that we still have LOS.
	if traceRes.Entity == self.Target && !self.Target:GetTable().asploded && self.Target:GetPos():Distance(self.Entity:GetPos())<self.FiringRange then
		self:Attack();
	else
		self:TargetSearch();
	end
end
end


function ENT:Lolthink ()
	if self.asploded or WMPause == true then return end
	self:DoMoves();
	self:DoAttacks();
end

function ENT:Think ()
	if (self.Healthlol < 1 && !self.asploded) then
	local expl=ents.Create("env_explosion")
		self:BeforeDeathFunc();
		expl:SetPos(self.Entity:GetPos());
		expl:SetOwner(self.Entity);
		expl:SetKeyValue("iMagnitude",self.DeathMagnitude);
		expl:SetKeyValue("iRadiusOverride", self.DeathRadius);
		expl:Spawn();
		expl:Activate();
		expl:Fire("explode", "", 0);
		expl:Fire("kill","",0);
		self.asploded = true;
		constraint.RemoveAll (self.Entity);
		self.Entity:SetColor (0, 0, 0, 255);
		self.Entity:Fire ("kill", "", 3);
	end
	self:OtherThoughts();
	if not (self.asploded or WMPause == true) then
		if (CurTime()>self.Loltiem) then
			self.Loltiem = CurTime()+self.Delay;
			self:DoAttacks();
				if (self:WaterLevel() >0 ) then
				local drowntime = server_settings.Int( "WM_Drowntime", 10 );
					if (self.Marine) then
					elseif ( drowntime == 0) then
					else
					self.Healthlol = self.Healthlol - self.Maxlol/drowntime*self.Delay - 1;
					end
				end
		end
		if self.Move then
		self:DoMoves();
		self.Entity:NextThink(CurTime());
		else
		self.Entity:NextThink(CurTime()+self.Delay);
		end
	end
	return true;
end

function ENT:TargetSearch ()
	if self.asploded then return end
	if WMPause == true then return end
	local entz = ents.FindByClass("info_target");
	for k, v in pairs(entz) do
		if v.Warmelon then
		local dist = v:GetPos():Distance(self.Entity:GetPos());
			if (dist<self.FiringRange && dist>self.MinRange && v.Team ~= self.Team && v:GetParent():GetTable().asploded ~= true) then
				local traceRes=util.QuickTrace (self.Entity:GetPos(), v:GetPos()-self.Entity:GetPos(), self.Entity);
				if traceRes.Entity == v:GetParent() then
				  if v.Team ~= nil && v.Team < 0 then
				    if math.random(0, 10) > 7 then
					  self.Target = v:GetParent();
					  break;
					  end
          else
					self.Target = v:GetParent();
					break;
					end
				end
			end
		end
	end
end

function ENT:OnTakeDamage (dmginfo)
	self.Entity:TakePhysicsDamage (dmginfo);
	self.Healthlol = self.Healthlol - dmginfo:GetDamage();
	if (self.Healthlol < 1 && !self.asploded) then
	local expl=ents.Create("env_explosion")
		self:BeforeDeathFunc();
		expl:SetPos(self.Entity:GetPos());
		expl:SetOwner(self.Entity);
		expl:SetKeyValue("iMagnitude",self.DeathMagnitude);
		expl:SetKeyValue("iRadiusOverride", self.DeathRadius);
		expl:Spawn();
		expl:Activate();
		expl:Fire("explode", "", 0);
		expl:Fire("kill","",0);
		self.asploded = true;
		constraint.RemoveAll (self.Entity);
		self.Entity:SetColor (0, 0, 0, 255);
		self.Entity:Fire ("kill", "", 3);
	end
	if self.Healthlol < self.Maxlol/5 && self.notflaming then
		self.trail = ents.Create("env_fire_trail");
		self.trail:SetPos (self.Entity:GetPos());
		self.trail:Spawn();
		self.trail:Activate();
		self.Entity:DeleteOnRemove(self.trail);
		self.trail:SetParent(self.Entity);
		self.notflaming = false;
	end
end
